<?php

class DocAction extends Action {
  private $_dev = 0;
  private $user=array();
  private $ACTION_CHECK=array('upload','savedoc','getdoc');
  private $_classify = array(
    hy => array(
        level =>array(
            1 => array(
                id => array(1,2,3,4,5,6,7,8,9,10),
                title => array('采矿业','石油天然气','建筑业','化学化工','基础设施与交通','电力','一般制造业','农业及农产品生产','林业','教科文商贸')
            ),
            2 => array()
        )
    ),
    zy => array(
        level =>array(
            1 => array(
                id => array(1,2,3,4,5,6,7),
                title => array('综合管理类','环境保护类','安全生产类','劳动卫生类','技术规范与标准类','产品标准类','国外法规类')
            ),
            2 => array()
        )
    )
  );
  function _initialize() {
    header("Content-Type:text/html; charset=UTF-8");
    $this->_dev = C("DEV_FLAG");
    $this->assign("istp", 1);//circle-header2中有TP和PHPWIND都用到，加上这个参数进行区别
    if (in_array(strtolower(ACTION_NAME),$this->ACTION_CHECK)) {
      $this->checkCookie();
    }
    $this->user['id']=$_COOKIE['tpxslmluserid'];
    $this->user['name']=$_COOKIE['tpxslmlusername'];
    $this->user['group_id']=$_COOKIE['tpxslmlgroupid'];
  }

  private function checkCookie() {
    //header('content-Type=text/html;charset=utf-8');
    $this->_dev = C("DEV_FLAG");
    $url = "http://localhost/aj2/pw8/login.php";
    if ($this->_dev == 0) $url = "http://www.ehs.cn/pw8/login.php";
    if(!$_COOKIE['tpxslmlusername'] and !$_COOKIE['tpxslmluserid'] and !$_COOKIE['tpxslmlgroupid'] and !$_COOKIE['tpxslmlrnd']) {
      redirect($url, 1, "您还没有登陆，请重新登陆，1秒后页面跳转~~");
      exit();
    }

  }
  /*文档首页*/
  public function index() {
    //$db=M("ADoc");
    //行业分类
    $m=M('AHy');
    $firstClass=$m->where('did=0')->select();

    $hyArr=array();
    foreach($firstClass as $first) {
      $hyArr[$first['id']]['title']=$first['title'];
      $items=$m->where('did='.$first['id'])
        ->select();
      $hyArr[$first['id']]['items']=$items;
    }
    //专业分类
    $m=M('AZy');
    $firstClass=$m->where('did=0')->select();
    $zyArr=array();
    foreach($firstClass as $first) {
      $zyArr[$first['id']]['title']=$first['title'];
      $items=$m->where('did='.$first['id'])
        ->select();
      $zyArr[$first['id']]['items']=$items;
    }

    //今日排行
    //select count(type_id) from a_member_download group by type_id where type=1;
    //$timeFrom=date('Y-m-d')." 00:00:00";
    //$timeTo=date('Y-m-d')." 23:59:59";
    //$map['datetime']=array('between',array($timeFrom,$timeTo));
    $map['type']=1;
    $m=M('AMemberDownload');
    $todayRank=$m->field('count(type_id),type_id as id,title')
      ->group('type_id')
      ->where($map)
      ->limit(20)
      ->select();

    //阅读排行
    $doc=M('ADoc');
    $readRank=$doc->field('id,read_num,title')
      ->order('read_num DESC')
      ->limit(20)
      ->select();

    //. echo $doc->getLastSQL();
    $latestCopy=$doc->where('ischeck=1 and isswf=1')
      ->order('add_time DESC')
      ->limit(20)
      ->select();

    //print_r($todayRank);
    $this->assign('latestCopy',$latestCopy);
    $this->assign('todayRank',$todayRank);
    $this->assign('readRank',$readRank);
    $this->assign('zyArr',$zyArr);
    $this->assign('hyArr',$hyArr);
    $this->display();
  }


  /*文档展示页*/
  public function docView() {
    // echo ACTION_NAME;
    //dump($this->user);
    $id=empty($_GET['id'])?0:$_GET['id'];
	$uid=empty($_COOKIE['tpxslmluserid'])?0:$_COOKIE['tpxslmluserid'];
	
    if(!$id) {
      $this->assign('jumpUrl','public.php/doc');
      $this->error('参数错误');
      exit();
    }
    $m=M('ADoc');
    $docItem=$m->find($id);

    if($docItem) {
      if(!$docItem['ischeck'] || !$docItem['isswf']) {
        $this->assign('message','文档暂时无法访问请稍候再试');
        $this->assign('jumpUrl','public.php?s=doc');
        $this->error('文档暂时无法访问请稍候再试');
      }
      //print_r($m);

      $fileArr= explode('\\',$docItem['file_url']);
      //dump($fileArr);
      $fileDate = $fileArr[3];
      $docItem['swf_url'] = "../admin_swf/".$fileDate."/".$docItem['swf_file_name'].".swf";
      //dump($docItem);
      $m->setInc("read_num","id={$id}");//增加阅读数量
      //$m->execute("update a_doc set read_num=read_num+1 where id={$id}");
      //echo ($m->getLastSQL());
      //$m->setField('read_num',"(read_num+1)")->where('id='.$id);//增加阅读数量
      //dump($docItem);
      //echo $path;
      //echo 	$docItem['grade_sum'].'/'.$docItem['grade_people_num'];

      $relatedDocs=$m->where("hy_id={$docItem['hy_id']} and id!={$id}")->limit('20')->order('update_time DESC')->select();
      $userDocs=$m->where("owner_id={$docItem['owner_id']} and id!={$id}")->limit('7')->order('update_time DESC')->select();
      //print_r($userDocs);
      $this->assign('docItem',$docItem);
	  $this->assign('uid',$uid);
      $this->assign('relatedDocs',$relatedDocs);
      $this->assign('userDocs',$userDocs);
      $this->display();
    }else {
      $this->assign('message','文档不存在');
      $this->assign('jumpUrl','public.php?s=doc');
      $this->error('文档不存在');
    }
  }

  /*获取文档下载AJAX*/
  public function setGradeAjax() {
    //$this->checkCookie();//检查用户登录状态
    $id=empty($_GET['id'])?0:$_GET['id'];
    $grade=empty($_GET['grade'])?0:$_GET['grade'];
    if(!$id || !$grade) {
      echo json_encode(array('result'=>'failed'));
      exit();
    }
    $m=M('ADoc');
    $m->setInc('grade_people_num',"id={$id}",1);
    $m->setInc('grade_sum',"id={$id}",$grade);
    //$m->execute("update a_doc set grade_sum=grade_sum+$grade where id={$id}");
    //$m->execute("update a_doc set grade_people_num=grade_people_num+1 where id={$id}");
    //m->setField('grade_people_num','(grade_people_num+1)')->where('id='.$id);
    //$m->setField('grade_sum',"grade_sum+{$grade}")->where('id='.$id);
    echo json_encode(array('result'=>'ok'));
  }


  /*文档下载*/
  public function getDoc() {

    $this->checkCookie();//检查用户登录状态
    $id=empty($_GET['id'])?0:$_GET['id'];
    if(!$id) {
      $this->assign('message','参数错误');
      $this->error('参数错误');
      exit();
    }

    /*检查文件有效性*/
    $m=M('ADoc');
    $docItem=$m->find($id);
    $docItem['file_url']=iconv('UTF-8','GB2312',$docItem['file_url']);
    if(!$docItem || empty($docItem['file_url']) /*|| !file_exists($docItem['file_url'])*/) {
      //exit($docItem['file_url']);
      $this->assign('message','文件不存在');
      $this->error('文件不存在');
      exit();
    }

    //检查用户积分余额
    $money=$this->_getUserMoney();
    if($docItem['price']>$money) {
      //exit($docItem['price'].'/'.$money);
      $this->assign('message','您的积分不足，无法进行下载');
      $this->error('您的积分不足，无法进行下载');
      exit();
    }


    $path=$docItem['file_url'];
    $path=str_replace('\\','/',$path);
    $pos=strpos($path,'www');
    $pos+=4;
    $sub=substr($path,0,$pos);
    $path=str_replace($sub,'',$path);
    $fName=substr($path,strrchr($path,'/'),1);
    //iconv("GB2312","UTF-8",$path);
    // exit("location:http://www.ehs.cn/".$path);
    //print_r($_COOKIE);
    // header("Content-Disposition:attachment;filename='{$fName}'");
    //$this->redirect("http://www.ehs.cn/".$path,'', 1,'下载中，请稍候~');
    echo iconv("GB2312","UTF-8","<script>location.href='http://www.ehs.cn/".$path."'</script>");
    $m->setInc('download_num',"id={$id}",1);
    @$this->_addDownLoadLog($id);
  }





  /*
  /*
  *$docId=用户下载文件id
  *1-存款，2-被下载，11-取款，12-下载
  记录用户积分记录
  返回用户积分余额*/
  private function _getUserMoney() {
    $money=0;
    if(empty($this->user['id']))return 0;
    else {
      $m=M('AMemberWealthLog');
      $items=$m->where("uid={$this->user['id']}")->order('type')->select();
      foreach($items as $item) {
        switch($item['type']) {
          case 1:$money+=$item['amount'];
            break;
          case 2:$money+=$item['amount'];
            break;
          case 11:$money-=$item['amount'];
            break;
          case 12:$money-=$item['amount'];
            break;
        }
      }//end for
    }  //end else
    return $money;
  }


  /*记录用户下载记录
  * $id,下载资料id
  */
  private function _addDownLoadLog($id) {
    //id/uid/type/type_id/title/price/datetime
    //[tpxslmlusername] => 3211 [tpxslmluserid] => 6177 [tpxslmlgroupid] => 1
    $m=M('ADoc');
    $doc=$m->find($id);
    $m=M('AMemberDownload');
    $data['uid']=$this->user['id'];
    $data['type']=1;//类型1，文档
    $data['type_id']=$doc['id'];
    $data['title']=$doc['title'];
    $data['price']=$doc['price'];
    $key=$m->add($data);
    ///$sql="insert into a_member_download(uid,type,type_id,title,price) values({$this->user['id']},{$doc['id']},{$doc['title']},{$doc['price']})";
    //dump($m->getLastSQL());
    //$key=$m->execute($sql);
    //$m->add($data);
    //$m->getLastInsId();
    if($key)$this->_addWealthLog($doc['id'],$key);
  }

  /*
  *$docId=用户下载文件id
  *1-存款，2-被下载，11-取款，12-下载
  记录用户积分记录
  */
  private function _addWealthLog($docId=0,$itemId) {
    //id/uid/type/type_id/price/amount/datetime
    if(empty($docId))return true;
    $m=M('ADoc');
    $doc=$m->find($docId);
    $data['uid']=$this->user['id'];
    $data['type']=12;
    $data['type_id']=$itemId;
    $data['price']=$doc['price'];
    $data['amount']=$doc['price'];
    $m=M('a_member_wealth_log');
    $m->add($data);//下载记录
    // dump($m->getLastSQL());exit();
    $conf=C('DOC_CREDIT_PERCENT');
    $data['type']=2;
    $data['uid']=$doc['owner_id'];
    $data['amount']=$doc['price']*$conf;
    $m->add($data);//被下载记录
    return true;
  }


  /*文档分类页,待改版*/
  public function categoryList() {
    $field=empty($_GET['zy'])?'':'zy_id';
    $field=(empty($field)&&!empty($_GET['hy']))?'hy_id':$field;
    // print_r($_GET);
    if(empty($field)) {
      $this->error('参数错误');
    }

    import("@.ORG.Page"); //导入分页类
    
    
	$ids=array();
	if($field=='zy_id'){
	   $kids=$this->_getFinalKids('AZy',$_GET['zy']);
	   foreach($kids as $kid)
	    $ids[]=$kid['id'];
	   if(count($ids))
	    $ids=implode(',',$ids);
	   else{
	     $ids=0;
	   }
	}elseif($field=='hy_id'){
	
	}
	
	
	$m=M('ADoc');
    switch($field) {
      case 'zy_id': {
          $list=$m->field('a_doc.id,a_doc.title')
            ->where("zy_id in($ids) and isswf=1 and ischeck=1")
            ->join('a_zy on a_doc.zy_id=a_zy.id')
            ->order('update_time DESC')
            ->select();
			//echo $m->getLastSQL();
          $p=new  Page(count($list),20);
          $list2=$m->field('a_doc.id,a_doc.title,add_time')
            ->where("zy_id in($ids) and isswf=1 and ischeck=1")
            ->order('update_time DESC')->limit("$p->firstRow,$p->listRows")
            ->join('a_zy on a_doc.zy_id=a_zy.id')
            ->select();
          $nav=$p->show();
        }
        break;
      case 'hy_id': {
          $list=$m->field('a_doc.id,a_doc.title')
            ->where("(hy_id={$_GET['hy']} or did={$_GET['hy']}) and isswf=1 and ischeck=1")
            ->join('a_hy on a_doc.hy_id=a_hy.id')
            ->order('update_time DESC')
            ->select();
          $p=new  Page(count($list),20);
          //dump($pager);
          $list2=$m->field('a_doc.id,a_doc.title,add_time')
            ->where("(hy_id={$_GET['hy']} or did={$_GET['hy']}) and isswf=1 and ischeck=1")
            ->join('a_hy on a_doc.hy_id=a_hy.id')
            ->order('update_time DESC')->limit("$p->firstRow,$p->listRows")->select();
          $nav=$p->show();
        }
        break;
      default:$list=array();
    }
     
    // echo $pager->listRows.'/'.$pager->firstRow;
    //dump($pager);
    //print_r($list);
    $this->assign('nav',$nav);
    $this->assign('list',$list2);
    $this->display('type_list');
  }


  /* public function index() {
    echo "<a href='".__URL__."/upload'>去上传测试吧！</a><br>";
    echo '<a href="'.__APP__.'/docPhotos/index">图片资料</a><br>';
    echo '<a href="'.__APP__.'/docVideos/index">视频资料</a>';
  }*/

  //上传文件
  public function upload() {
    if ($_FILES) {
      $doc = $_FILES['file'];
      $file = $this->checkDoc($doc);
      $fileUrl = $file["file_url"];
      $fileSize	= $file['file_size'];
      $title = $file['title'];
      $ownerID = $_COOKIE["tpxslmluserid"];
      $ownerName = $_COOKIE["tpxslmlusername"];
      $rt = array('file_url'=>$fileUrl,'file_size'=>$fileSize,'owner_id'=>$ownerID,'owner_name'=>$ownerName,'zy'=>$zy,'hy'=>$hy,'title'=>$title);
      $this->assign("file", $rt);
      $hzr = $this->_getHZRList(array('a_hy','a_zy'));/*,'a_region'*/
      $this->assign('hzr', $hzr);
      $hl = $this->_classify['hy']['level'][1]['id'];
      $zl = $this->_classify['zy']['level'][1]['id'];
	  
      $this->assign('hl', json_encode($hl));
      $this->assign('zl', json_encode($zl));
      $this->display('upload-detail');
	  //exit('f');
      /*    $file_info_arr = FL::upload_flash($doc);
      $file_url	=	$file_info_arr['file_url'];
      $filesize	=	$file_info_arr['filesize'];
      $title		=	$file_info_arr['title'];
      //	$title		=	$file_info_arr[]
      //行业
      $hy =$_TSGLOBAL['db']->findAll('select * from a_hy');
      //专业
      //	$zy =$_TSGLOBAL['db']->findAll('select * from a_zy');
      $zy =$_TSGLOBAL['db']->findAll('select * from a_zy');
      $a = cat_list($zy,0,-1,0);
      $zy = implode('',$GLOBALS['var']);

      $arr = array(
              'file_url'=>$file_url,'filesize'=>$filesize,'winduid'=>$winduid,'windid'=>$windid,'zy'=>$zy,'hy'=>$hy,'title'=>$title
      );

      modules_contr_Pub::assign($arr);
      modules_contr_Pub::display('show_make_swf.html'); */
    }else {
      $this->display();
    }

  }


  private function _getHZRList($table) {
    $m = M();
    $rt = array();
    foreach ($table as $k => $v) {
      $list = $m->query("select * from $v");
      $rt[$k] = $this->_reList(array(),$list,0);
    }
    return $rt;
  }


  private function _reList($rt,$list,$did) {
    foreach ($list as $k => $v) {
      if ($did == $v["did"]) {
        $rt[$k] = array(id=>$v["id"],title=>$v["title"],law_count=>$v['law_count'],downLine=>array());
        $rt[$k]["downLine"] = $this->_reList(array(),$list,$v['id']);
      }
    }
    return $rt;
  }

  private function checkDoc($doc) {
    $allow_type = array('application/msword','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'application/octet-stream','application/vnd.ms-powerpoint','text/plain','application/pdf','application/vnd.ms-powerpoint','application/vnd.ms-excel');
    $hz_name_arr=array('doc','xls','ppt','txt','pdf','pptx','docx','xlst');
    //if($doc['error']==0) {
    $name		=	$doc["name"];
    $temp_str	=	strrev($name);
    $len		=	strpos($temp_str,'.');  //后辍名长度
    $hz_name	=	substr($temp_str,0,$len);
    $hz_name	=	strrev($hz_name);//后缀名
    if(!in_array($hz_name,$hz_name_arr)) {
      echo "<script language=javascript>  alert('错误的格式，第一个错误');location.href='".__URL__."/upload'</script>";
      exit();
    }
    $type=$doc['type'];
    if(!in_array($type,$allow_type)) {
      echo "<script language=javascript>  alert('错误的格式，第二个错误');location.href='".__URL__."/upload'</script>";
      exit();

    }
    $size = $doc['size'];
    if($size>1024*1024*20)  //20480KB=20M
    {
      echo "<script language=javascript>  alert('你上传的文件过大');location.href='".__URL__."/upload'</script>";
      exit();
    }
    elseif ($size==0) {
      echo "<script language=javascript>  alert('你上传的文件过大小为0');location.href='".__URL__."/upload'</script>";
      exit();

    }
    $new_name = time().rand(1000,9999);//四种取后缀的方法
    $appendix=".".$hz_name;
    //$file = '../pw8/user_gr/attachments/flash/'.'jo_'.date("Ymd").'/';
    $file = "E:\www\admin_temp_doc\\";
    if ($this->_dev == 1) $file = "D:\wamp\www\admin_temp_doc\\";
    //alert("D:\wamp\www\admin_temp_doc\\".$new_name.$appendix);
    if(!file_exists($file)) {
      $rt = mkdir($file);//windows 或Linux都会出现文件超过5000时会丢失或出错 或查找困难所以要分目录
    }

    move_uploaded_file($doc['tmp_name'],$file.$new_name.$appendix);
    $return_arr["file_size"]	=$doc['size'];
    $return_arr["file_url"]	= $file.$new_name.$appendix;
    $return_arr["title"]	= $doc['name'];
    return $return_arr;
    //}

  }

  public function saveDoc() {
    $m = M("ADoc");
    $data = $_POST;
    $data["add_time"] = time();
    unset($data["__hash__"]);
    $rt = $m->add($data);
//    $url = __URL__."/upload";
//    if ($this->_dev == 0) $url = "http://www.ehs.cn/pw8/user_gr/index.php";
    $url = __ROOT__."/user.php/index/index/type/4/menu/2";
    if ($rt > 0) {
      redirect($url, 1, "上传成功，1秒后页面跳转~~");
    }else  echo "<script language=javascript>  alert('上传出错');location.href='".__URL__."/upload'</script>";
  }
  
  
    /*
	返回第三级子分类
	@table=表名称；@pid=分类id，数组或者数字
	*/
  private function _getFinalKids($table,$pid){
    $m=M($table);
	if(!is_array($pid))
		$list=$m->field('id')->where("did=".$pid)->select();
	else {
	    $ids=implode(',',$pid);
		$list=$m->field('id')->where("did in($ids)")->select();
	  }
	 
	if($list) {
	   foreach($list as $li)
	     $ids[]=$li['id'];
	     $list=$this->_getFinalKids($table,$ids);
	   }
	 else{
	   if(!is_array($pid))
		$list=$m->where("id=".$pid)->select();
	  else {
	    $ids=implode(',',$pid);
		$list=$m->where("id in($ids)")->select();
	   }
	  }
	return $list; 
  }

}
?>
